package homework2.NearestPoints;

import java.util.ArrayList;

/**
 * Calculate nearest points via brute force method
 * 
 * @author eDisOn 2009212634 lilh09@mails.tsinghua.edu.cn
 * 
 */
public class BruteForceAlgorithm
{
	ArrayList<Point> points = new ArrayList<Point>();

	public BruteForceAlgorithm()
	{

	}

	public ArrayList<NearestPoints> exec(ArrayList<Point> initPoints)
	{
		points = initPoints;
		return findNearestPoints(points);
	}

	public ArrayList<NearestPoints> findNearestPoints(ArrayList<Point> points)
	{
		ArrayList<NearestPoints> nearestPointsArray = new ArrayList<NearestPoints>();

		double minDist = Integer.MAX_VALUE;

		for (int i = 0; i < points.size() - 1; i++)
		{
			Point firPoint = points.get(i);
			for (int j = i + 1; j <= points.size() - 1; j++)
			{
				Point secPoint = points.get(j);
				double distance = calcDistance(firPoint, secPoint);

				if (distance < minDist)
				{
					minDist = distance;
					nearestPointsArray.clear();
					nearestPointsArray.add(new NearestPoints(firPoint,
							secPoint, minDist));
				}
				else if (distance == minDist)
				{
					nearestPointsArray.add(new NearestPoints(firPoint,
							secPoint, minDist));
				}
				else
				{
					// DO NOTHING!!!
				}
			}
		}

		return nearestPointsArray;
	}

	private double calcDistance(Point firPoint, Point secPoint)
	{
		return Math.sqrt(Math.pow(firPoint.x - secPoint.x, 2)
				+ Math.pow(firPoint.y - secPoint.y, 2));
	}

	public String getResult(ArrayList<NearestPoints> nearestPointsArr)
	{
		int index = 1;
		String display = "";
		display += "There are " + nearestPointsArr.size()
				+ " pair/pairs nearest points exist\n";
		display += "Minimum distance is : " + nearestPointsArr.get(0).distance
				+ "\n";
		for (NearestPoints nearestPoints : nearestPointsArr)
		{
			display += index++ + ".Points:(" + nearestPoints.firPoint.x + ","
					+ nearestPoints.firPoint.y + ") & ("
					+ nearestPoints.secPoint.x + "," + nearestPoints.secPoint.y
					+ ")";
			display += "\n";
		}
		return display;
	}
}
